package Gui;

import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import client.ConnectionClient;

/**
 * MedicalRecordGUI is the user interface to the medical record client.
 * It sets up the main window and connects to connection client.
 */
public class MedicalRecordGUI {
	/**
	 * cc is the database object
	 */
	private final ConnectionClient cc;

	/**
	 * tabbedPane is the contents of the window. It consists of three panes, User
	 * login, View records and Add records.
	 */
	private final JTabbedPane tabbedPane;

	/**
	 * Create a GUI object and connect to the connection client.
	 * 
	 * @param cc
	 *            The connection client.
	 */
	public MedicalRecordGUI(ConnectionClient cc) {
		this.cc = cc;

		JFrame frame = new JFrame("Medical records");
		tabbedPane = new JTabbedPane();

		UserLoginPane userLoginPane = new UserLoginPane(cc);
		tabbedPane.addTab("User login", null, userLoginPane,
				"Log in as a new user");

		MedicalRecordPane bookingPane = new MedicalRecordPane(cc);
		tabbedPane.addTab("View Medical Records", null, bookingPane,
				"Medical Records");

		AppendRecordPane appendRecordPane = new AppendRecordPane(cc);

		tabbedPane.addTab("Add Medical Records", null, appendRecordPane,
				"Add Medical Records");
		tabbedPane.setSelectedIndex(0);

		frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);

		tabbedPane.addChangeListener(new ChangeHandler());
		frame.addWindowListener(new WindowHandler());

		frame.setSize(800, 600);

		frame.setVisible(true);

		userLoginPane.displayMessage("Connecting to database ...");
	}

	/**
	 * ChangeHandler is a listener class, called when the user switches panes.
	 */
	class ChangeHandler implements ChangeListener {
		/**
		 * Called when the user switches panes. The entry actions of the new
		 * pane are performed.
		 * 
		 * @param e
		 *            The change event (not used).
		 */
		public void stateChanged(ChangeEvent e) {
			BasicPane selectedPane = (BasicPane) tabbedPane
					.getSelectedComponent();
			selectedPane.entryActions();
		}
	}

	/**
	 * WindowHandler is a listener class, called when the user exits the
	 * application.
	 */
	class WindowHandler extends WindowAdapter {
		/**
		 * Called when the user exits the application. Closes the connection to
		 * the database.
		 * 
		 * @param e
		 *            The window event (not used).
		 */
		@Override
		public void windowClosing(WindowEvent e) {
			cc.closeConnection();
			System.exit(0);
		}
	}
}
